<template>
  <div class="box">
    <el-switch style="display: block" v-model="value" active-color="#13ce66" inactive-color="#13ce66" active-text="时间"
      inactive-text="公里标" @change="change"></el-switch>
    <div class="chart" ref="chartsItem" id="chartsItem"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: {
    list: {
      type: Object,
      default () {
        return {};
      }
    },
    videoTime: {
      type: Number,
      default: 0
    },
    progressValue: {
      type: Number,
      default: 0
    },
    startT: {
      type: String,
      default: ''
    },
    openWholeRecord: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      datasList: [],
      data1: [],
      data2: [],
      data3: [],
      colors: ['#5470C6', '#EE6666', '#ffff00'],
      currentList: [],
      storageList: [],
      value: true,
      kilometer: [],
      myChart: null,
      pointIcon: 'https://img.alicdn.com/imgextra/i1/2200676927379/O1CN01JvuVeR24NdXxskaNO_!!2200676927379.png',
      currentIndex: 0,
      interval: null,
      timeout: null
    };
  },
  mounted () {
    this.initializeData();
    this.initializeChart();
    this.currentTime = this.formatTooltip(this.progressValue)
    window.addEventListener('resize', this.monitorSize)
  },
  methods: {
    getDatestamp(val){
      var timeString = val; // 时分秒字符串
      var currentDate = new Date(); // 当前日期对象
      var dateString = currentDate.toDateString(); // 获取当前日期的字符串表示（不包含时分秒）
      var dateTimeString = dateString + ' ' + timeString; // 拼接日期和时分秒字符串
      var timestamp = Date.parse(dateTimeString); // 将日期时间字符串转换为时间戳
      return timestamp
    },
    debounce(event) {
      // 清除已经设置的timeout
      clearTimeout(this.timeout);
 
      // 设置新的timeout以在输入结束后0.5秒执行
      this.timeout = setTimeout(() => {
        // 在这里处理输入结束后的逻辑
        event
      }, 500);
    },
    monitorSize(){
      var that = this
      this.debounce(that.myChart.resize())
    },
    strainer(value, type) {
        const dt = new Date(value)
        // 返回年数的四位数方法
        const y = dt.getFullYear()
        // 月份从0开始，所有要加1，如果不足两位用es6字符串方法补0
        const m = (dt.getMonth() + 1 + '').padStart(2, '0')
        const d = (dt.getDate() + '').padStart(2, '0')

        const hh = (dt.getHours() + '').padStart(2, '0')
        const mm = (dt.getMinutes() + '').padStart(2, '0')
        const ss = (dt.getSeconds() + '').padStart(2, '0')
        if(type === 'yyyy-MM-dd'){
        return `${y}-${m}-${d}`
        }else if(type === 'hh:mm'){
        return `${hh}:${mm}`
        }else if(type === 'HH:mm:ss'){
        return `${hh}:${mm}:${ss}`
        }else if(type === 'yyyy年MM月'){
        return `${y}年${m}月`
        }else {
        return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
        }
    },
    formatTooltip(val) {
      let value = Number(this.getTimestamp(this.startT)) + val
      return this.strainer(value,'HH:mm:ss')
    },
    getTimestampStr(val){
      var timeString = val; // 时分秒字符串
      var currentDate = new Date(); // 当前日期对象
      var dateString = currentDate.toDateString(); // 获取当前日期的字符串表示（不包含时分秒）
      var dateTimeString = dateString + ' ' + timeString; // 拼接日期和时分秒字符串
      var timestamp = Date.parse(dateTimeString); // 将日期时间字符串转换为时间戳
      return timestamp
    },
    initializeData () {
      let arr = [];
      let newarr = [];
      Object.keys(this.list).forEach(item => {
        arr.push(this.getTimestamp(item));
      });
      newarr = arr.sort((a, b) => a - b);
      newarr.forEach(item => {
        this.datasList.push(this.timestampToTime(item));
        this.storageList.push(this.timestampToTime(item));
        this.currentList.push(this.timestampToTime2(item));
      });
      Object.values(this.list).forEach(item => {
        this.kilometer.push(item.encode22);
        this.data1.push(item.encode16);
        this.data2.push(item.encode26);
        this.data3.push('120');
      });
    },
    getTimestamp (val) {
      return Math.floor(new Date(val).getTime() / 1000);
    },
    timestampToTime (timestamp) {
      var date = new Date(timestamp * 1000);
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      return h + m + s;
    },
    timestampToTime2 (timestamp) {
      var date = new Date(timestamp * 1000);
      var Y = date.getFullYear() + "-";
      var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    initializeChart () {
      const chartDom = this.$refs.chartsItem;
      this.myChart = echarts.init(chartDom);
      let arr  = JSON.parse(JSON.stringify(this.storageList)) 
      this.currentIndex = 0;
      let timestampS = Number(this.getTimestampStr(this.startT)) + this.progressValue
      let i = this.findNextSmallerValue(this.datasList,this.currentIndex,timestampS)
      this.datasList.forEach((item,index) => {
        if(item == i){
          this.currentIndex = index
        }
      })
      arr = arr.splice(this.currentIndex,20)
      

      const option = {
        color: this.colors,
        tooltip: {
          trigger: 'none',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {},
        grid: {
          top: 70,
          bottom: 50
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: arr
        },
        yAxis: [
          {
            name: '管压KPA',
            type: 'value'
          },
          {
            name: '速度km/h',
            nameLocation: 'start',
            alignTicks: true,
            type: 'category',
            inverse: true,
            data: [150, 120, 90, 60, 30, 0]
          }
        ],
        series: [
          {
            name: '速度km/h',
            type: 'line',
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.data1.reverse()
          },
          {
            name: '管压力KPA',
            type: 'line',
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.data2.reverse()
          },
          {
            name: '限速',
            type: 'line',
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.data3
          }
        ],
        graphic: [
          {
            type: 'image',
            id: 'movingIcon',
            left: '9%', // Initial value
            top: '49%',
            z: 100,
            bounding: 'raw',
            style: {
              image: this.pointIcon,
              width: 40,
              height: 40,
            }
          }
        ]
      };
      this.myChart.setOption(option);
      this.myChart.on('click', params => {
        let times = ''
        this.currentList.forEach(item => {
          if(this.getDatestamp(item.split(' ')[1]) === this.getDatestamp(params.name)){
            times = item
          }
        })
        this.$emit('clickIdxChart', times);
      });
    },
    startIconMovement () {
        if (this.datasList[this.currentIndex] != this.datasList[this.datasList.length-1]&&this.currentIndex<this.datasList.length) {
          // 计算图标的位置
          let str = this.datasList[this.currentIndex]
          const xPixel = this.myChart.convertToPixel('xAxis', str);
          const chartWidth = this.myChart.getWidth();
          this.storageList = JSON.parse(JSON.stringify(this.datasList))
          let arr  = JSON.parse(JSON.stringify(this.storageList)) 
          arr.shift();
          let newarr = []
          arr.forEach((item,index) => {
            if(this.currentIndex>10){
              if(index>=(this.currentIndex-10)&&index<(this.currentIndex+10)){
                newarr.push(item)
              }
            } else if(index>=this.currentIndex&&index<(this.currentIndex+20)) {
              newarr.push(item)
            }
          })
          if(newarr.length<20){
            newarr = arr.splice((arr.length-19),20)
          }
          this.myChart.setOption({
            color: this.colors,
            tooltip: {
              trigger: 'none',
              axisPointer: {
                type: 'cross'
              }
            },
            legend: {
              textStyle: {
                  color: '#ffffff' // 这里设置图例的字体颜色为白色
              }
            },
            grid: {
              top: 70,
              bottom: 50
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: newarr
            },
            yAxis: [
              {
                name: '管压KPA',
                type: 'value'
              },
              {
                name: '速度km/h',
                nameLocation: 'start',
                alignTicks: true,
                type: 'category',
                inverse: true,
                data: [150, 120, 90, 60, 30, 0]
              }
            ],
            series: [
              {
                name: '速度km/h',
                type: 'line',
                smooth: true,
                emphasis: {
                  focus: 'series'
                },
                data: this.data1.reverse()
              },
              {
                name: '管压力KPA',
                type: 'line',
                smooth: true,
                emphasis: {
                  focus: 'series'
                },
                data: this.data2.reverse()
              },
              {
                name: '限速',
                type: 'line',
                smooth: true,
                emphasis: {
                  focus: 'series'
                },
                data: this.data3
              }
            ],
            graphic: [
              {
                id: 'movingIcon',
                type: 'image', // Ensure 'type' is set
                z: 100,
                style: {
                  image: this.pointIcon,
                  width: 40,
                  height: 40,
                  x: xPixel + (this.currentIndex>10?0:200), // Adjust x position to center icon
                  y: this.myChart.getHeight() * 0.6 - 20 // Adjust y position to center icon
                }
              }
            ]
          },true); // Force update to refresh the graphic
        } else {
          let times = (this.currentList[this.currentList.length-1])
          this.$emit('clickIdxChart', times);
        }
    },
    change (e) {
      this.value = e;
      const xAxisData = this.value ? this.datasList : this.kilometer;
      this.myChart.setOption({
        xAxis: {
          data: xAxisData
        }
      });
    },
    findNextSmallerValue(arr, currentIndex,timestampS) {
      if (currentIndex === arr.length - 1) {
        return null; // 当前元素已是数组的最后一个，没有下一个更大的值
      }
      for (let i = 0; i < arr.length; i++) {
        // console.log('this.getTimestampStr(arr[i)',this.getTimestampStr(arr[i]),timestampS,this.getTimestampStr(arr[i+1]),this.getTimestampStr(arr[i])<timestampS,timestampS<=this.getTimestampStr(arr[i+1]))
        if (this.getTimestampStr(arr[i])<timestampS&&timestampS<=this.getTimestampStr(arr[i+1])) {
          return arr[i+1]; // 找到下一个更小的值
        }
      }
      return 0; // 没有找到更小的值
    }
  },
  watch:{
  'progressValue':{
    handler(newV,OldV){
      let storageIndex = this.currentIndex
      if(newV&&newV!=OldV){
        let timestampS = Number(this.getTimestampStr(this.startT)) + newV
        let i = this.findNextSmallerValue(this.datasList,this.currentIndex,timestampS)
        this.datasList.forEach((item,index) => {
          if(item == i){
            if(index!=storageIndex){
              this.currentIndex = index;
              this.startIconMovement()
            }
          }
        })
      }
    },
    deep:true
  },
  'openWholeRecord':{
    handler(newV,OldV){
      if (newV!=OldV) {
        this.monitorSize()
      }
    }
  }
}
};
</script>

<style scoped>
.box {
  width: 100%;
  height: 90%;
}

.chart {
  width: 100%;
  height: 100%;
}

/deep/.el-switch {
  padding-right: 20px;
  display: flex !important;
  justify-content: flex-end;
}
</style>